﻿using Md.Api.DDD;
using Md.Api.Entity.DapperModels.MdDB;
using Md.Api.Model.Web.MdUser.Request;
using Md.Dapper.Repositories.Md;
using Md.Redis.Repositories;

namespace Md.Api.Service.Web.MdUser;
/// <summary>
/// 用户注册服务
/// </summary>
public class RegisterMdUserWebService : ApiBase<RequestRegisterMdUserWebModel>
{
    /// <summary>
    /// 用户仓储
    /// </summary>
    public MdUserRep mdUserRep { get; set; }
    /// <summary>
    /// redis缓存
    /// </summary>
    public MdRedisService _redisService { get; set; }
    /// <summary>
    /// 执行
    /// </summary>
    protected override void ExecuteMethod()
    {
        if (string.IsNullOrWhiteSpace(_redisService.Instance.Get(Parameter.CodeUuid)))
        {
            throw new AggregateException("验证码已超时");
        }

        if (Parameter.Code != _redisService.Instance.Get(Parameter.CodeUuid))
        {
            throw new AggregateException("验证码不正确");
        }

        var model = new MdUserModel();

        if (Parameter.RegisterMode == "1")
        {
            if (string.IsNullOrWhiteSpace(Parameter.UserName))
            {
                throw new AggregateException("用户名不能为空");
            }

            model.UserNick = Parameter.UserName;
            model.UserName = Parameter.UserName;

            var userNameExits = mdUserRep.CheckUserNameUnique(model.UserName);

            if (Convert.ToInt32(userNameExits) > 0)
            {
                throw new AggregateException("用户名已存在");
            }
        }

        if (Parameter.RegisterMode == "2")
        {
            if (string.IsNullOrWhiteSpace(Parameter.Email))
            {
                throw new AggregateException("邮箱不能为空");
            }

            model.UserNick = Parameter.Email;
            model.Email = Parameter.Email;

            var emailExits = mdUserRep.CheckEmailUnique(model.Email);

            if (Convert.ToInt32(emailExits) > 0)
            {
                throw new AggregateException("邮箱已存在");
            }
        }

        if (Parameter.RegisterMode == "3")
        {
            if (string.IsNullOrWhiteSpace(Parameter.Phone))
            {
                throw new AggregateException("手机号不能为空");
            }

            model.UserNick = Parameter.Phone;
            model.Phone = Parameter.Phone;

            var phoneExits = mdUserRep.CheckPhoneUnique(model.Phone);

            if (Convert.ToInt32(phoneExits) > 0)
            {
                throw new AggregateException("手机号已存在");
            }
        }

        model.UserPwd = EncrptyHelp.MD5Pwd(Parameter.UserPwd);
        model.UserType = "00";
        model.CreateBy = "1";
        model.CreateTime = DateTime.Now;
        model.OnLine = "2";
        model.Status = "0";
        model.DelFlag = "0";

        var res = mdUserRep.Insert(model);

        var user = mdUserRep.GetMdUserByUserId(res);

        if (res > 0 && user != null)
        {
            // uuid需要存缓存，uuid对应用户信息
            var uuid = Guid.NewGuid().ToString();

            var userDict = new Dictionary<string, object>
            {
                { "userId", user.UserId},
                { "uuid", uuid },
                { "platform", 2 }
            };

            _redisService.Instance.Set($"{user.UserId}_{userDict["platform"]}", uuid);

            var token = JwtHelp.SetJwtEncode(userDict, Convert.ToDouble(JsonConfig.JsonRead("MdSettings:TokenExpire")));

            _redisService.Instance.Set($"{user.UserId}Token_{userDict["platform"]}", token);

            Result.Data = new { user, token };
        }
        else
        {
            Result.Data = "注册失败,请联系管理员";
        }
    }
}

